/*
 * @Author: lijing
 * @e-mail: 1413979079@qq.com
 * @LastEditors: lijing
 * @Date: 2019-10-09 16:40:05
 * @LastEditTime: 2020-05-15 12:56:38
 * @FilePath: \client\src\main.js
 * @Description: 入口文件
 */

import Vue from 'vue'
import App from './App'
import router from './router'
// BootstrapVue
import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
// mavonEditor
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
// vue-echarts
import ECharts from 'vue-echarts'
// axios实例
import axios from '@/request/http.js'
import urls from '@/request/url.js'
// vuex
import store from "@/store/index";


// 为了方便调用，将api加到Vue的原型链上
Vue.prototype.$axios = axios;
// 将v-chart注册为全局组件
Vue.component('v-chart', ECharts)
Vue.use(BootstrapVue)
Vue.use(mavonEditor)
Vue.config.productionTip = false

// BootstrapIcons
import { BootstrapVueIcons } from 'bootstrap-vue'
import 'bootstrap-vue/dist/bootstrap-vue-icons.min.css'
Vue.use(BootstrapVueIcons)

import { VueShowdown } from 'vue-showdown'
Vue.component('VueShowdown', VueShowdown)


function checkCommToken() {
  let commToken = store.state.app.commToken;
  if (commToken) {
    axios
      .get(urls.comm.userInfo, {
        params: {
          token: commToken
        }
      })
      .then(res => {
        store.commit('setCommToken', commToken);
        store.commit('setUserInfo', res.data);
      }).catch(err => {
        window.localStorage.removeItem("comm_token");
      });
  }
}

function checkAdminToken() {
  let adminToken = store.state.app.adminToken;
  if (adminToken) {
    axios.get(urls.admin.token, { params: { token: adminToken } })
      .then(res => {
        console.log(res);
      })
      .catch(err => {
        store.commit('setAdminToken', "");
      })
  }
}

function checkLocationToken() {
  let search = window.location.search;
  if (search && search.startsWith("?token=")) {
    const token = search.split("=")[1];
    store.commit('setCommToken', token);
    router.replace("/");
  }
}

var instance = new Vue({
  router,
  store,
  render: h => h(App),
  created() {
    checkLocationToken();
    axios.get(urls.comm.initCheck)
      .then(res => {
        res = res.data;
        if (res.code == 20000) {
          checkCommToken();
          checkAdminToken();
          store.dispatch('getBlogInfo')
        } else {
          router.replace("/init/user");
        }
      });
  }
}).$mount('#app')

export default instance;
